# FILE: GeoCodingBroker.py
# DESC: obtains geo coding for LSAEntry object using google geo coder 
#
import urllib, sys

from WebServiceBroker import WebServiceBroker

#TODO: move to oreus.conf

GOOGLE_GEO_CODER_URL="http://maps.google.com/maps/geo?output=json&oe=utf-8&mapclient=jsapi&q=%s&key=ABQIAAAA_0hAzy4dbwijHMCZEOJ-XBStNkmczT10EsTokrjT4KAT0QQIgxRZl68X5OJEjvGyV5yLIMrI2fp0DA"
G_GEO_SUCCESS = 200

class GeoCodingBroker(WebServiceBroker):

	def geoCodeLocation(self, location):
		lat = None
		lng = None
		accuracy = None 
								
		try:		
			response = self.requestJSON(GOOGLE_GEO_CODER_URL % urllib.quote_plus(location.encode('utf-8')))
			if response and response['Status']['code'] == G_GEO_SUCCESS and response['Placemark']:
				placemark = response['Placemark'][0]									
				lat = placemark['Point']['coordinates'][1]
				lng = placemark['Point']['coordinates'][0]
				accuracy = placemark['AddressDetails']['Accuracy']										
		except Exception, e:
			sys.stderr.write("failed to geocode location %s, reason %s" % (location, e))
			
		return (lat, lng, accuracy)